<template>
	<view class="container">
		<!-- 操作工具栏 -->
		<view class="toolbar">
			<button class="create-btn" @click="showCreateDialog">+ 新建活动</button>
		</view>

		<!-- 活动列表 -->
		<scroll-view class="activity-list" scroll-y>
			<view v-for="activity in activities" :key="activity.id" class="activity-card"
				:class="{ 'disabled': !activity.enabled }">
				<view class="card-header">
					<text class="title">{{ activity.name }}</text>
					<switch :checked="activity.enabled" @change="toggleActivityStatus(activity)" color="#4CAF50" />
				</view>

				<view class="card-body">
					<!-- 活动类型 -->
					<view class="info-row">
						<uni-icons type="notification" size="16" color="#666" />
						<text class="type-tag" :class="activity.type">
							{{ typeMap[activity.type] }}
						</text>
					</view>

					<!-- 时间范围 -->
					<view class="info-row">
						<uni-icons type="calendar" size="16" color="#666" />
						<text>{{ formatDate(activity.start_time) }} 至 {{ formatDate(activity.end_time) }}</text>
					</view>

					<!-- 优惠规则 -->
					<view class="rule-preview">
						<text v-if="activity.type === 'FULL_REDUCE'">
							满{{ activity.condition_amount }}减{{ activity.discount_amount }}
						</text>
						<text v-if="activity.type === 'PERCENT'">
							{{ activity.discount_percent }}%折扣
						</text>
						<text v-if="activity.type === 'DIRECT'">
							立减{{ activity.discount_amount }}元
						</text>
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="card-footer">
					<button class="edit-btn" @click="editActivity(activity)">编辑</button>
					<button class="delete-btn" @click="deleteActivity(activity.id)">删除</button>
				</view>
			</view>
		</scroll-view>

		<!-- 活动表单弹窗 -->
		<uni-popup ref="formDialog" type="dialog">
			<view class="form-dialog">
				<text class="dialog-title">{{ isEditMode ? '编辑活动' : '新建活动' }}</text>

				<view class="form-content">
					<view class="form-item">
						<text class="label">活动名称</text>
						<input v-model="formData.name" placeholder="请输入活动名称" />
					</view>

					<view class="form-item">
						<text class="label">活动类型</text>
						<picker mode="selector" :range="typeOptions" range-key="label" @change="handleTypeChange">
							<view class="type-picker">
								{{ typeMap[formData.type] || '请选择活动类型' }}
								<uni-icons type="arrowdown" size="14" color="#666" />
							</view>
						</picker>
					</view>

					<!-- 动态规则表单 -->
					<template v-if="formData.type === 'FULL_REDUCE'">
						<view class="form-item">
							<text class="label">满减条件</text>
							<input v-model="formData.condition_amount" type="number" placeholder="请输入满减金额" />
							<text class="unit">元</text>
						</view>
						<view class="form-item">
							<text class="label">减免金额</text>
							<input v-model="formData.discount_amount" type="number" placeholder="请输入减免金额" />
							<text class="unit">元</text>
						</view>
					</template>

					<template v-if="formData.type === 'PERCENT'">
						<view class="form-item">
							<text class="label">折扣比例</text>
							<input v-model="formData.discount_percent" type="number" placeholder="请输入折扣比例" />
							<text class="unit">%</text>
						</view>
					</template>

					<template v-if="formData.type === 'DIRECT'">
						<view class="form-item">
							<text class="label">立减金额</text>
							<input v-model="formData.discount_amount" type="number" placeholder="请输入立减金额" />
							<text class="unit">元</text>
						</view>
					</template>

					<view class="form-item">
						<text class="label">活动时间</text>
						<view class="time-picker">
							<picker mode="date" fields="datetime" :value="formData.start_time"
								@change="(e) => formData.start_time = e.detail.value">
								<view class="time-item">
									{{ formData.start_time || '开始时间' }}
								</view>
							</picker>
							<text>至</text>
							<picker mode="date" fields="datetime" :value="formData.end_time"
								@change="(e) => formData.end_time = e.detail.value">
								<view class="time-item">
									{{ formData.end_time || '结束时间' }}
								</view>
							</picker>
						</view>
					</view>
				</view>

				<view class="dialog-actions">
					<button class="cancel-btn" @click="closeDialog">取消</button>
					<button class="confirm-btn" @click="submitForm">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue'

	import {
		queryActivities
	} from '../../request/api.js'
	
	import {
		useUserStore
	}from '../../stores/user.js'

	onMounted(async () => {
		const res = await queryActivities(useUserStore().student_id)
		console.log(res)
		activities.value = res.activities
	})

	// 活动类型配置
	const ACTIVITY_TYPES = {
		FULL_REDUCE: '满减',
		PERCENT: '折扣',
		DIRECT: '立减'
	}

	const typeMap = computed(() => ACTIVITY_TYPES)
	// 类型选项用于选择器
	const typeOptions = computed(() =>
		Object.entries(ACTIVITY_TYPES).map(([value, label]) => ({
			value,
			label
		}))
	)

	// 初始表单数据
	const initFormData = () => ({
		id: null,
		name: '',
		type: '',
		condition_amount: null,
		discount_amount: null,
		discount_percent: null,
		start_time: '',
		end_time: '',
		enabled: true
	})

	// 响应式数据
	const activities = ref([])
	const formData = reactive(initFormData())
	const isEditMode = ref(false)
	const formDialog = ref(null)

	// 表单验证规则
	const validateForm = () => {
		if (!formData.name) {
			uni.showToast({
				title: '请填写活动名称',
				icon: 'none'
			})
			return false
		}

		if (!formData.type) {
			uni.showToast({
				title: '请选择活动类型',
				icon: 'none'
			})
			return false
		}

		if (formData.type === 'FULL_REDUCE' && (!formData.condition_amount || !formData.discount_amount)) {
			uni.showToast({
				title: '请填写满减条件',
				icon: 'none'
			})
			return false
		}

		if (formData.type === 'PERCENT' && !formData.discount_percent) {
			uni.showToast({
				title: '请填写折扣比例',
				icon: 'none'
			})
			return false
		}

		if (formData.type === 'DIRECT' && !formData.discount_amount) {
			uni.showToast({
				title: '请填写立减金额',
				icon: 'none'
			})
			return false
		}

		if (!formData.start_time || !formData.end_time) {
			uni.showToast({
				title: '请选择活动时间',
				icon: 'none'
			})
			return false
		}

		return true
	}

	// 提交表单
	const submitForm = async () => {
		if (!validateForm()) return

		const payload = {
			...formData
		}
		console.log(payload)
		try {
			if (isEditMode.value) {
				// 调用更新接口
				const index = activities.value.findIndex(a => a.id === payload.id)
				activities.value.splice(index, 1, payload)
			} else {
				// 调用创建接口
				payload.id = Date.now()
				activities.value.unshift(payload)
			}

			closeDialog()
			uni.showToast({
				title: '保存成功'
			})
		} catch (error) {
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		}
	}

	// 打开创建对话框
	const showCreateDialog = () => {
		Object.assign(formData, initFormData())
		isEditMode.value = false
		formDialog.value.open()
	}

	// 编辑活动
	const editActivity = (activity) => {
		Object.assign(formData, activity)
		isEditMode.value = true
		formDialog.value.open()
	}

	// 删除活动
	const deleteActivity = (id) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该活动吗？',
			success: (res) => {
				if (res.confirm) {
					activities.value = activities.value.filter(a => a.id !== id)
				}
			}
		})
	}

	// 切换活动状态
	const toggleActivityStatus = (activity) => {
		activity.enabled = !activity.enabled
	}

	// 关闭对话框
	const closeDialog = () => {
		formDialog.value.close()
	}

	// 工具函数
	const formatDate = (dateStr) => {
		if (!dateStr) return ''
		const date = new Date(dateStr)
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
	}

	// 修改处理类型变化的方法
	const handleTypeChange = (e) => {
		const selected = Object.keys(ACTIVITY_TYPES)[e.detail.value]
		formData.type = selected
	}
</script>

<style scoped>
	/* 样式设计 */
	.container {
		padding: 10px;
		background: #f8f9fa;
		min-height: 100vh;
	}

	.toolbar {
		margin-bottom: 20px;
		position: fixed;
	}

	.create-btn {
		background: #4CAF50;
		color: white;
		border-radius: 8px;
		
	}

	.activity-list {
		position: relative;
		margin-top: 50px;
		height: calc(100vh - 100px);
	}

	.activity-card {
		background: white;
		border-radius: 12px;
		padding: 16px;
		margin-bottom: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	.disabled {
		opacity: 0.6;
		background: #f5f5f5;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.title {
		font-size: 16px;
		font-weight: 500;
	}

	.type-tag {
		padding: 2px 8px;
		border-radius: 4px;
		font-size: 12px;
		margin-left: 8px;
	}

	.type-tag.FULL_REDUCE {
		background: #fff7e6;
		color: #fa8c16;
	}

	.type-tag.discount_percent {
		background: #f6ffed;
		color: #52c41a;
	}

	.type-tag.DIRECT {
		background: #fff0f6;
		color: #eb2f96;
	}

	.info-row {
		display: flex;
		align-items: center;
		margin: 8px 0;
		color: #666;
	}

	.rule-preview {
		margin: 12px 0;
		padding: 8px;
		background: #f8f9fa;
		border-radius: 6px;
	}

	.card-footer {
		display: flex;
		gap: 8px;
		margin-top: 12px;
	}

	.edit-btn {
		background: #1890ff;
		color: white;
	}

	.delete-btn {
		background: #ff4d4f;
		color: white;
	}

	/* 表单弹窗样式 */
	.form-dialog {
		background: white;
		padding: 24px;
		border-radius: 12px;
		width: 85vw;
	}

	.dialog-title {
		font-size: 18px;
		font-weight: 500;
		margin-bottom: 20px;
		display: block;
	}

	.form-item {
		margin-bottom: 16px;
	}

	.label {
		display: block;
		color: #666;
		margin-bottom: 8px;
	}

	input {
		border: 1px solid #eee;
		border-radius: 6px;
		padding: 8px;
		width: 100%;
	}

	.unit {
		margin-left: 8px;
		color: #999;
	}

	.time-picker {
		display: flex;
		gap: 8px;
		align-items: center;
	}

	.time-item {
		padding: 8px;
		border: 1px solid #eee;
		border-radius: 6px;
	}

	.dialog-actions {
		display: flex;
		gap: 12px;
		margin-top: 24px;
	}

	.confirm-btn {
		background: #4CAF50;
		color: white;
		flex: 1;
	}

	.cancel-btn {
		background: #f5f5f5;
		color: #666;
		flex: 1;
	}
</style>